<template>
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="visible" width="800px">
        <el-form ref="form" :model="form" label-width="auto">
            <el-form-item label="告警类型" prop="alarmType">
                <el-radio-group v-model="form.alarmType" @change="changeAlarmType" :disabled="isEditOrCopy">
                    <el-radio :label="it.value" v-for="it of alarmTypeList" :key="it.value">{{ it.label }}</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
        <AON v-if="form.alarmType === 'AON'" @getParentList="getParentList" :bu-model-list="buModelList"
            :filter="filter" :code-desc-list="codeDescList" :allOrgUsers="allOrgUsers" :role-list="roleList" ref="AON"
            :title="title" :factory-list="factoryList" :visible="visible" :tableRow="tableRow" />
        <DefectQty v-else-if="form.alarmType === 'DefectQty'" @getParentList="getParentList"
            :bu-model-list="buModelList" :code-desc-list="codeDescList" :allOrgUsers="allOrgUsers" :role-list="roleList"
            ref="DefectQty" :title="title" :factory-list="factoryList" :visible="visible" :tableRow="tableRow" />
        <DefectConsecutiveRise v-else-if="form.alarmType === 'DefectConsecutiveRise'" @getParentList="getParentList"
            :bu-model-list="buModelList" :code-desc-list="codeDescList" :allOrgUsers="allOrgUsers" :role-list="roleList"
            ref="DefectConsecutiveRise" :title="title" :factory-list="factoryList" :visible="visible"
            :tableRow="tableRow" />
        <MapFocus v-else-if="form.alarmType === 'MapFocus'" @getParentList="getParentList" :bu-model-list="buModelList"
            :code-desc-list="codeDescList" :allOrgUsers="allOrgUsers" :defect-map-type-list="defectMapTypeList"
            :role-list="roleList" ref="MapFocus" :title="title" :visible="visible" :tableRow="tableRow" />
        <div slot="footer" v-loading="loading">
            <el-button @click="visible = false">取消</el-button>
            <el-button type="primary" @click="sureAdd">确定</el-button>
        </div>
    </el-dialog>
</template>
<script>
import { fetchAllRolePage, getOrgTree } from "@/api/authOrgnaization";
import {
    addAlarmConfigure,
    updateAlarmConfigure,
} from "@/api/alarm.config";
import {
    attachUsersToTree,
    fetchAllUsersByDept,
    getAllLeafDeptIds,
} from '@/utils/alarm.utils'
import AON from './AON.vue'
import DefectQty from './DefectQty.vue'
import DefectConsecutiveRise from './DefectConsecutiveRise.vue'
import MapFocus from './MapFocus.vue'

export default {
    components: { AON, DefectQty, DefectConsecutiveRise, MapFocus },
    props: ['filter', 'alarmTypeList', 'codeDescList', 'buModelList', 'factoryList', 'defectMapTypeList'],
    name: "addDialog",
    computed: {
        isEditOrCopy() {
            return ['编辑', '复制'].includes(this.title)
        }
    },
    data() {
        return {
            tableRow: {},
            title: '新增',
            loading: false,
            roleList: [],
            visible: false,
            form: {
                alarmType: ""
            },
            orgList: [],
            allOrgUsers: [],
            loadingOrg: true,
        }
    },
    async created() {
        this.getRoleList()
        await this.initFullTree()
    },
    methods: {
        changeAlarmType() {
            this.$nextTick(_ => {
                this.$refs && this.$refs.form.clearValidate()
            })
        },
        filterTreeForOld(tree) {
            return (tree || [])
                .filter(node => {
                    // 如果没有 name 字段，就直接保留
                    if (!node.boeOrgName) return true;
                    return !node.boeOrgName.endsWith("*");
                })
                .map(node => ({
                    ...node,
                    children: node.children ? this.filterTreeForOld(node.children) : []
                }))
        },
        async initFullTree() {
            if (!localStorage.getItem('allUserByOrgTree')) {
                const { data } = await getOrgTree()
                let orgTree = this.filterTreeForOld(data)
                const leafDeptIds = getAllLeafDeptIds(orgTree)
                const allUsers = await fetchAllUsersByDept(leafDeptIds)
                this.allOrgUsers = attachUsersToTree(orgTree, allUsers)
                localStorage.setItem('allUserByOrgTree', JSON.stringify(this.allOrgUsers))
            } else {
                this.allOrgUsers = this.filterTreeForOld(JSON.parse(localStorage.getItem('allUserByOrgTree')))
            }
            this.loadingOrg = false
        },

        async show(type, row) {
            if (type === 'add') {
                this.title = '新增'
            } else {
                this.form.id = type === 'edit' ? row.id : ''
                this.title = type === 'edit' ? '编辑' : '复制'
                this.tableRow = row
            }
            this.form.alarmType = this.filter
            this.visible = true
        },
        sureAdd() {
            this.$refs.form.validate(valid => {
                if (valid) {
                    let params = this.$refs[this.form.alarmType].getParams()
                    if (!params) {
                        return
                    }
                    let funcAction;
                    this.loading = true
                    if (this.title === '编辑') {
                        funcAction = updateAlarmConfigure(params, this.form.id)
                    } else if (['新增', '复制'].includes(this.title)) {
                        funcAction = addAlarmConfigure(params)
                    }
                    funcAction.then(_ => {
                        this.$message({
                            type: 'success',
                            message: '操作成功'
                        })
                        this.visible = false
                        this.loading = false
                        this.$emit('getParentList')
                    }).catch(err => {
                        this.loading = false
                    })
                }
            })
        },
        getParentList() {
            this.$emit('getParentList')
        },
        getRoleList() {
            fetchAllRolePage({ pageNum: 1, pageSize: 20, sortBody: 'id|asc' }).then(res => {
                this.roleList = res.data.records
            })
        }
    }
}
</script>